/* 
 * Copyright (C) 2001-2003 Jacek Sieka, j_s@telia.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#if !defined(AFX_UPLOADMANAGER_H__B0C67119_3445_4208_B5AA_938D4A019703__INCLUDED_)
#define AFX_UPLOADMANAGER_H__B0C67119_3445_4208_B5AA_938D4A019703__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "UserConnection.h"
#include "Singleton.h"

#include "ClientManagerListener.h"
#include <deque>
#include "File.h"

class Upload : public Transfer, public Flags {
public:
	enum Flags {
		FLAG_USER_LIST = 0x01,
		FLAG_SMALL_FILE = 0x02,
		FLAG_ZUPLOAD = 0x04
	};

	typedef Upload* Ptr;
	typedef vector<Ptr> List;
	typedef List::iterator Iter;
	
	Upload() : file(NULL) { }
	virtual ~Upload() { 
		delete file;
	}
	
	User::Ptr& getUser() { dcassert(getUserConnection() != NULL); return getUserConnection()->getUser(); }
	
	GETSET(string, fileName, FileName);
	GETSET(string, localFileName, LocalFileName);
	GETSET(InputStream*, file, File);
};

class UploadManagerListener {
public:
	virtual ~UploadManagerListener() { }
	template<int I>	struct X { enum { TYPE = I };  };
	
	typedef X<0> Complete;
	typedef X<1> Failed;
	typedef X<2> Starting;
	typedef X<3> Tick;
	typedef X<4> WaitingAddFile;
	typedef X<5> WaitingRemoveUser;

	virtual void on(Starting, Upload*) throw() { }
	virtual void on(Tick, const Upload::List&) throw() { }
	virtual void on(Complete, Upload*) throw() { }
	virtual void on(Failed, Upload*, const string&) throw() { }
	virtual void on(WaitingAddFile, const User::Ptr, const string&) throw() { }
	virtual void on(WaitingRemoveUser, const User::Ptr) throw() { }

};

class UploadManager : private ClientManagerListener, private UserConnectionListener, public Speaker<UploadManagerListener>, private TimerManagerListener, public Singleton<UploadManager>
{
public:
	
	/** @return Number of uploads. */ 
	int getUploads() { Lock l(cs); return uploads.size(); }

	/**
	 * @remarks This is only used in the tray icons. Could be used in
	 * MainFrame too.
	 *
	 * @return Average download speed in Bytes/s
	 */
	int getAverageSpeed() {
		Lock l(cs);
		int avg = 0;
		for(Upload::Iter i = uploads.begin(); i != uploads.end(); ++i) {
			Upload* u = *i;
			avg += (int)u->getRunningAverage();
		}
		return avg;
	}
	
	//int getRunning() { return running; };
	int getFreeSlots() { return max((SETTING(SLOTS) - running), 0); }
	int getFreeExtraSlots() { return max(3 - getExtra(), 0); };
	
	void reserveSlot(const User::Ptr& aUser, u_int32_t grant_time = 600*1000) {
		Lock l(cs);
		reservedSlots[aUser] = GET_TICK() + grant_time;
	}

	//typedef deque<User::Ptr> SlotQueue;
	//typedef set<string> FileSet;
	//typedef hash_map<User::Ptr, FileSet, User::HashFunction> FilesMap;
	//string getQueue() const;
	//void clearUserFiles(const User::Ptr&);
	//const SlotQueue& getQueueVec() const;
	//const FileSet& getQueuedUserFiles(const User::Ptr &) const;

	/** @internal */
	void addConnection(UserConnection::Ptr conn) {
		conn->addListener(this);
		conn->setState(UserConnection::STATE_GET);
	}

	//void notifyQueuedUsers();
	//void clearQueue() { waitingUsers.clear(); waitingFiles.clear(); }
	//void setRunning(int _running) { running = _running; /*notifyQueuedUsers();*/ }
	GETSET(int, running, Running);
	GETSET(int, extra, Extra);
	GETSET(u_int32_t, lastAutoGrant, LastAutoGrant);

	// Upload throttling
	bool throttle();
	size_t throttleGetSlice();
	size_t throttleCycleTime();

private:
	//int running;
	void throttleZeroCounters();
	void throttleBytesTransferred(u_int32_t i);
	void throttleSetup();
	bool mThrottleEnable;
	size_t	mBytesSent,
			mBytesSpokenFor,
			mUploadLimit,
			mCycleTime,
			mByteSlice;

	Upload::List uploads;
	CriticalSection cs;

	typedef HASH_MAP<User::Ptr, u_int32_t, User::HashFunction> SlotMap;
	typedef SlotMap::iterator SlotIter;
	SlotMap reservedSlots;

	//functions for manipulating waitingFiles and waitingUsers
	//SlotQueue waitingUsers;		//this one merely lists the users waiting for slots
	//FilesMap waitingFiles;		//set of files which this user's searched for
	//void addFailedUpload(UserConnection::Ptr source, string filename);

	friend class Singleton<UploadManager>;
	UploadManager() throw();
	virtual ~UploadManager() throw();

	void removeConnection(UserConnection::Ptr aConn);
	void removeUpload(Upload* aUpload);

	// ClientManagerListener
	virtual void on(ClientManagerListener::Types type, const User::Ptr& aUser) throw();
	
	// TimerManagerListener
	virtual void on(TimerManagerListener::Second, u_int32_t aTick) throw();
	virtual void on(TimerManagerListener::Minute, u_int32_t aTick) throw();

	// UserConnectionListener
	virtual void on(UserConnectionListener::GetListLength, UserConnection*) throw();
	virtual void on(UserConnectionListener::Send, UserConnection*) throw();
	virtual void on(UserConnectionListener::TransmitDone, UserConnection*) throw();
	virtual void on(UserConnectionListener::BytesSent, UserConnection*, size_t, size_t);
	virtual void on(UserConnectionListener::Failed, UserConnection*, const string&);
	virtual void on(UserConnectionListener::Get, UserConnection*, const string&, int64_t);
	virtual void on(UserConnectionListener::GetBlock, UserConnection*, const string&, int64_t, int64_t) throw();
	virtual void on(UserConnectionListener::GetZBlock, UserConnection*, const string&, int64_t, int64_t) throw();

	void onGetZBlock(UserConnection* aSource, const string& aFile, int64_t aResume, int64_t aBytes);
	void onGetBlock(UserConnection* aSource, const string& aFile, int64_t aResume, int64_t aBytes, bool z);

	bool prepareFile(UserConnection* aSource, const string& aFile, int64_t aResume, int64_t aBytes);

	bool doubleCheckNickForSlot(const string userName) ;
};

#endif // !defined(AFX_UPLOADMANAGER_H__B0C67119_3445_4208_B5AA_938D4A019703__INCLUDED_)
/**
 * @file
 * $Id: UploadManager.h 336 2005-09-05 23:18:00Z Pothead $
 */